from flask import Flask, render_template_string
from flask_socketio import SocketIO, send

# 创建Flask应用和SocketIO实例
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

# HTML 模板，包含前端聊天室界面
html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Local Chat Room</title>
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; }
        #chat { max-width: 600px; margin: 0 auto; padding: 20px; }
        #message-box { border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll; background-color: #fff; }
        #message-box p { margin: 5px 0; }
        #input-box { margin-top: 10px; }
        #input-box input { width: 80%; padding: 10px; }
        #input-box button { padding: 10px; }
    </style>
</head>
<body>
    <div id="chat">
        <h2>Local Chat Room</h2>
        <div id="message-box"></div>
        <div id="input-box">
            <input type="text" id="message-input" placeholder="Type your message...">
            <button onclick="sendMessage()">Send</button>
        </div>
    </div>

    <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
    <script type="text/javascript">
        var socket = io();

        // 接收从服务器发来的消息
        socket.on('message', function(msg) {
            var messageBox = document.getElementById('message-box');
            var newMessage = document.createElement('p');
            newMessage.textContent = msg;
            messageBox.appendChild(newMessage);
            messageBox.scrollTop = messageBox.scrollHeight;
        });

        // 发送消息到服务器
        function sendMessage() {
            var input = document.getElementById('message-input');
            var message = input.value;
            if (message.trim() !== "") {
                socket.send(message);
                input.value = '';
            }
        }

        // 按 Enter 键发送消息
        document.getElementById("message-input").addEventListener("keypress", function(event) {
            if (event.key === "Enter") {
                sendMessage();
            }
        });
    </script>
</body>
</html>
"""

# 路由显示聊天室页面
@app.route('/')
def chat():
    return render_template_string(html)

# 当客户端发送消息时，广播消息给所有客户端
@socketio.on('message')
def handle_message(msg):
    print('Received message: ' + msg)
    send(msg, broadcast=True)

# 启动服务器
if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, debug=True)